package com.saas.auth.handler;

import com.pig4cloud.pig.admin.api.entity.SysLog;
import com.pig4cloud.pig.common.core.constant.CacheConstants;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import com.pig4cloud.pig.common.log.event.SysLogEvent;
import com.pig4cloud.pig.common.log.util.SysLogUtils;
import com.pig4cloud.pig.common.security.handler.AbstractAuthenticationSuccessEventHandler;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@RequiredArgsConstructor
public class PigAuthenticationSuccessEventHandler extends AbstractAuthenticationSuccessEventHandler {
	private final StringRedisTemplate stringRedisTemplate;

	/**
	 * 处理登录成功方法
	 * <p>
	 * 获取到登录的authentication 对象
	 * @param authentication 登录对象
	 */
	@Override
	public void handle(Authentication authentication) {
		if(Objects.isNull(authentication)){
			return;
		}
		log.info("用户：{} 登录成功", authentication.getPrincipal());

		//先执行登录成功后执行过滤器，故此时租户ID为null
		PigUser pigUser = SecurityUtils.getUser(authentication);
		String username = Objects.isNull(pigUser) ? null : pigUser.getUsername();

		SysLog logVo = SysLogUtils.getSysLog(null);
		logVo.setTitle("登录成功");
		logVo.setServiceId(authentication.getName());
		logVo.setCreateBy(username);
		SpringContextHolder.publishEvent(new SysLogEvent(logVo));
		Integer tenantId = Objects.isNull(pigUser) ? null : pigUser.getTenantId();
		log.info("用户当前租户ID：{}", tenantId);
		//记录用户最近登录的租户（包含切换租户）
		if(tenantId != null && StringUtils.isNotBlank(username)){
			log.info("设置用户：{} 最后使用租户：{}", username, tenantId);
			stringRedisTemplate.opsForValue().set(CacheConstants.TELNET_LASTTIME_KEY_ + username, String.valueOf(pigUser.getTenantId()));
		}
	}

}
